<!-- @format -->

<template>
  <div class="textbook-content" v-html="processedContent"></div>
</template>

<script>
  import katex from 'katex'
  import 'katex/dist/katex.min.css'
  import DOMPurify from 'dompurify'

  export default {
    props: {
      content: {
        type: String,
        required: true,
      },
    },
    computed: {
      processedContent() {
        const sanitized = DOMPurify.sanitize(this.content)
        return this.renderTextbookMath(sanitized)
      },
    },
    methods: {
      renderTextbookMath(html) {
        // 预处理特殊符号
        // html = html.replace(/\\angle/g, '∠')
        // html = html.replace(/\\overset\{\\frown\}\{([^}]*)\}/g, '⌒$1')

        // 智能上下标处理
        html = this.enhanceSubSuperScripts(html)

        // 教科书样式配置（特别优化上下标）
        const textbookStyle = {
          displayMode: true,
          throwOnError: false,
          macros: {
            '\\lim': '\\lim\\limits',
            '\\sin': '\\text{sin}',
            '\\cos': '\\text{cos}',
            '\\tan': '\\text{tan}',
            '\\to': '\\rightarrow',
            '\\rac': '\\frac',
            // 移除对上下标符号的转义，这会阻止KaTeX正确解析上下标
            // _: '\\textunderscore',
            // '^': '\\textasciicircum',
          },
          fleqn: true,
          minRuleThickness: 0.06,
          strict: false,
        }

        // 处理所有数学表达式
        const patterns = [
          {
            regex: /\\\((.*?)\\\)/g,
            options: { ...textbookStyle, displayMode: false },
          },
          { regex: /\\\[(.*?)\\\]/gs, options: textbookStyle },
          {
            regex: /\$(.*?)\$/g,
            options: { ...textbookStyle, displayMode: false },
          },
          { regex: /\$\$(.*?)\$\$/gs, options: textbookStyle },
        ]

        patterns.forEach(({ regex, options }) => {
          html = html.replace(regex, (match, latex) => {
            try {
              // 自动修正常见错误
              latex = latex.replace(/\\rac/g, '\\frac')
              latex = latex.replace(/\\taNx/g, '\\tan x')

              // 特别优化上下标表达式
              latex = this.optimizeSubSuperScripts(latex)

              return katex.renderToString(latex, options)
            } catch (e) {
              console.warn('渲染失败:', e.message)
              return `<span class="math-error">${match}</span>`
            }
          })
        })

        return html
      },

      enhanceSubSuperScripts(html) {
        // 处理简单上标（非数学模式中的^）- 改进正则表达式
        html = html.replace(/([a-zA-Z0-9])\^([a-zA-Z0-9]+)/g, '$1<sup>$2</sup>')

        // 处理简单下标（非数学模式中的_）- 改进正则表达式
        // 注意：不处理数学公式中的下标，只处理普通文本中的下标
        // 排除$...$和$$...$$内的内容
        const mathBlocks = [];
        const mathRegexes = [
          /\$\$(.*?)\$\$/gs,
          /\$(.*?)\$/g,
          /\\\[(.*?)\\\]/gs,
          /\\\((.*?)\\\)/g
        ];
        
        // 临时替换数学公式块
        let tempHtml = html;
        mathRegexes.forEach((regex, index) => {
          tempHtml = tempHtml.replace(regex, (match) => {
            const placeholder = `__MATH_PLACEHOLDER_${index}_${mathBlocks.length}__`;
            mathBlocks.push(match);
            return placeholder;
          });
        });
        
        // 在非数学区域处理下标
        tempHtml = tempHtml.replace(
          /([a-zA-Z0-9])_([a-zA-Z0-9]+)/g,
          '$1<sub>$2</sub>'
        );
        
        // 恢复数学公式块
        mathBlocks.forEach((block, index) => {
          const regex = new RegExp(`__MATH_PLACEHOLDER_\\d+_${index}__`, 'g');
          tempHtml = tempHtml.replace(regex, block);
        });
        
        return tempHtml;
      },

      optimizeSubSuperScripts(latex) {
        // 确保上标使用花括号包裹多字符 - 修复正则表达式
        latex = latex.replace(/\^\{([^}]+)\}/g, '^{$1}') // 保留已有的花括号
        latex = latex.replace(/\^([^{\s])/g, '^{$1}') // 为单字符添加花括号

        // 确保下标使用花括号包裹多字符 - 修复正则表达式
        latex = latex.replace(/_\{([^}]+)\}/g, '_{$1}') // 保留已有的花括号
        latex = latex.replace(/_([^{\s])/g, '_{$1}') // 为单字符添加花括号

        // 处理嵌套上下标 - 修复正则表达式
        latex = latex.replace(/([_^])\{(.*?)\}([_^])\{/g, '$1{$2}$3{')
        
        // 处理连续的上下标
        latex = latex.replace(/\^\{([^}]*)\}_\{([^}]*)\}/g, '^{$1}_{$2}')
        latex = latex.replace(/_\{([^}]*)\}\^\{([^}]*)\}/g, '_{$1}^{$2}')

        return latex
      },
    },
  }
</script>

<style scoped>
  .textbook-content {
    font-size: 17px;
    line-height: 1.8;
    font-family: 'Times New Roman', 'SimSun', serif;
    color: #333;
  }

  .textbook-content .katex {
    font-size: 1.15em;
    font-family: 'KaTeX_Main', 'Times New Roman', serif;
  }

  /* 上标特别样式 */
  .textbook-content .katex .sup {
    top: -0.5em;
    font-size: 0.85em;
    position: relative;
    vertical-align: baseline;
  }

  .textbook-content .katex .sup > .cbox {
    position: relative;
    display: inline-block;
  }

  /* 下标特别样式 */
  .textbook-content .katex .sub {
    bottom: -0.25em;
    font-size: 0.85em;
    position: relative;
    vertical-align: baseline;
  }

  .textbook-content .katex .sub > .cbox {
    position: relative;
    display: inline-block;
  }

  /* 上下标组合样式 */
  .textbook-content .katex .sizing {
    display: inline-block;
    position: relative;
  }

  .textbook-content .katex .vlist {
    display: inline-block;
  }

  .textbook-content .katex-display {
    margin: 1.5em 0;
    padding: 0.5em 1em;
    background-color: #f9f9f9;
    border-radius: 4px;
    overflow-x: auto;
    overflow-y: hidden;
  }

  .textbook-content .katex-display > .katex {
    padding: 0.5em 0;
    display: inline-block;
    min-width: 100%;
  }

  .textbook-content .math-error {
    color: #c7254e;
    background-color: #f9f2f4;
    padding: 2px 4px;
    border-radius: 3px;
    border: 1px dashed #c7254e;
  }

  /* 极限符号特别样式 */
  .textbook-content .limop {
    margin-bottom: 0.1em;
  }

  .textbook-content .limits > .vlist-t {
    display: inline-table;
    table-layout: fixed;
  }
</style>
